package com.xiemingtian.navdemo.code

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import androidx.navigation.NavAction
import androidx.navigation.NavController
import androidx.navigation.NavGraph
import androidx.navigation.fragment.FragmentNavigator
import com.xiemingtian.navdemo.Loader
import com.xiemingtian.navdemo.R
import com.xiemingtian.navdemo.Util

class CodeNavActivity : AppCompatActivity() {

    private lateinit var navController : NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_code_nav)

        val finalHost = buildNavigation()

        supportFragmentManager.beginTransaction()
                .replace(R.id.nav_host, finalHost)
                .setPrimaryNavigationFragment(finalHost)
                .commit()
    }

    private fun buildNavigation() : Fragment {
        navController = NavController(this)

        navController.navigatorProvider.addNavigator(FragmentNavigator(this, supportFragmentManager , R.id.nav_host))

        val graph = NavGraph(navController.navigatorProvider)

        var startId = -1
        var finalHost = Fragment()

        for (i in 0 until Loader.destinations.size()){
            val id = Loader.destinations.keyAt(i).toInt()
            val e = Loader.destinations.valueAt(i)
            val dest =  FragmentNavigator.Destination(navController.navigatorProvider)
            dest.fragmentClass = e.aClass
            dest.id = id
            val actions = e.actions
            val dests = e.dest
            if (actions.size == dests.size){
                for (j in actions.indices){
                    val action = actions[i]
                    val d = dests[j]
                    dest.putAction(action, NavAction(d, Util.navOpt))
                }
            }
            if (e.isStart && startId == -1){
                startId = id
                finalHost = e.aClass.newInstance()
            }
            else{
                Log.e("CodeNavActivity","multi start")
            }
            graph.addDestination(dest)
        }

        if (startId == -1){
            startId = Id.f1
            finalHost = CodeFragment1()
        }

        graph.startDestination = startId
        navController.graph = graph

        return finalHost
    }

    fun getNavController() : NavController{
        return navController
    }
}

object Id{
    const val f1 = 1

    const val a1 = 2

    const val f2 = 3

    const val f3 = 4
}